package com.oocl.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.oocl.pojo.Merchant;
import com.oocl.pojo.Protocol;
import com.oocl.service.MerchantManager;
import com.oocl.service.factory.MerchantManagerFactory;
import com.oocl.util.DESUtil;
import com.oocl.util.JSONUtil;

@WebServlet("/getMerchant")
public class GetMerchantsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private MerchantManager merchantManager;
    private Logger logger = Logger.getLogger(GetMerchantsServlet.class);
	
    public GetMerchantsServlet() {
        super();
        merchantManager = MerchantManagerFactory.getInstance();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = response.getWriter();
		List<Merchant> merchants = merchantManager.findMerchantByIsban(false);
		if(!merchants.isEmpty()){
			List<String> merchantIdList = new ArrayList<String>();
			for(Merchant merchant:merchants){
				String id = merchant.getId();
				merchantIdList.add(id);
			}
			Protocol protocol = new Protocol(merchantIdList);
			String json = JSONUtil.toJSON(protocol);
			DESUtil desUtil = new DESUtil();
			json = desUtil.encrypt(json, "UTF-8");
			writer.write(json);
			logger.info("customer get merchant list");
		} else {
			Protocol protocol = new Protocol(new String("Can't get merchant list"));
			String json = JSONUtil.toJSON(protocol);
			writer.write(json);
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
